using System.IO;
using UnityEditor;
using UnityEngine;

namespace DTFramework.Editor
{
    /// <summary>
    /// 用脚本创建ScriptableObject 资源文件
    /// </summary>
    public class CreateScriptableAsset : MonoBehaviour
    {
        [InitializeOnLoadMethod]
        static void InitializeOnLoadMethod()
        {
            EditorApplication.projectWindowItemOnGUI = (guid, selectionRect) =>
            {
                // 在 Project 视图中选择一个资源   
                if (Selection.activeObject && Selection.activeObject.name.Contains("SO") && guid == AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(Selection.activeObject)))
                {
                    var _name = Selection.activeObject.name;
                    var path = AssetPath.GetScriptableAsset(_name);

                    if (File.Exists(path) || Selection.activeObject is ScriptableObject)
                    {
                        return;
                    }
                    //设置拓展按钮区域     
                    float width = 70f;
                    selectionRect.x += (selectionRect.width - width);
                    // selectionRect.y += 1f;
                    selectionRect.width = width;
                    GUI.color = Color.green;
                    //点击事件   
                    if (GUI.Button(selectionRect, "ReflashReference SO"))
                    {
                        var testData = ScriptableObject.CreateInstance(Selection.activeObject.name);
                        AssetDatabase.CreateAsset(testData, path);
                        Debug.Log($"创建 {_name} 对象成功！");
                        AssetDatabase.Refresh();
                    }
                    GUI.color = Color.white;
                }
            };
        }
    }
}